<?php

namespace App\Kuafu\WaiMai\Model;

use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\Base\Model\Traits\KfWaiMaiSplit;
use App\Kuafu\WaiMai\Enum\WaiMaiCodeEnum;
use App\Kuafu\WaiMai\Exceptions\WaiMaiException;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Kuafu\Base\Model\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasMany;

class WaiMaiShopFinishConfigModel extends BaseModel
{
    use HasFactory;
    use KfUid;

    protected $connection = 'mysqlWaiMaiAll';
    protected $table      = 'waimai_shop_finish_config'; //表名
    protected $primaryKey = 'id';
    public    $timestamps = true;

    protected $fillable = [
        'shopId',
        'timeId',
        'priceType',
        'seconds',
    ];

    const PRICE_TYPE_1 = 1; // 小额订单出餐
    const PRICE_TYPE_2 = 2; // 中额订单出餐
    const PRICE_TYPE_3 = 3; // 大额订单出餐

    // priceType对应金额范围，左闭右开，金额分
    const PRICE_TYPE_NUM = [
        self::PRICE_TYPE_1 => [0, 5000],
        self::PRICE_TYPE_2 => [5000, 10000],
        self::PRICE_TYPE_3 => [10000, 999999999],
    ];

    /**
     * 获取priceType的中文描述
     * @return string
     * @throws WaiMaiException
     */
    public function getPriceTypeTextAttribute(): string
    {
        return self::getPriceTypeText($this->priceType);
    }

    /**
     * 获取priceType的中文描述 - 底层手动调用
     * @param int $priceType
     * @return string
     * @throws WaiMaiException
     */
    public static function getPriceTypeText(int $priceType)
    {
        $numRange  = self::PRICE_TYPE_NUM[$priceType];
        $numRange0 = $numRange[0] / 100;
        $numRange1 = $numRange[1] / 100;

        switch ($priceType) {
            case self::PRICE_TYPE_1:
                $res = "默认小额订单出餐（<{$numRange1}）";
                break;
            case self::PRICE_TYPE_2:
                $res = "默认中额订单出餐（{$numRange0}-{$numRange1}）";
                break;
            case self::PRICE_TYPE_3:
                $res = "默认大额订单出餐（>{$numRange0}）";
                break;
            default:
                throw new WaiMaiException(WaiMaiCodeEnum::ERR_PRICE_TYPE);
        }

        return $res;
    }

    public static function addData(int $shopId, int $timeId, int $priceType, int $seconds)
    {
        return self::query()
                   ->create([
                       'shopId'    => $shopId,
                       'timeId'    => $timeId,
                       'priceType' => $priceType,
                       'seconds'   => $seconds
                   ]);
    }

    public static function delData(int $shopId)
    {
        return self::query()
                   ->where('shopId', $shopId)
                   ->delete();
    }
}
